--
-- Author: shunguo.chen
-- Date: 2016-06-20 12:47:35
--
-- IMRoomView

local TabsBtn = require("app.widget.TabsBtn")
local ListViewExtend = require("app.widget.ListViewExtend")

local IMBoxPanel = import(".IMBoxPanel")
local IMMsgRender = import(".renders.IMMsgRender")
local IMVoiceRender = import(".renders.IMVoiceRender")
local IMPriRender = import(".renders.IMPriRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

local MESSAGE_MAX_NUM = 80

ClassRef.VIEW_ROOT_RES = Res.IMRoomScene

function ClassRef:init()
	local width = self._root:getChildByName("im"):getContentSize2()
	self._initPosX = - width - display.safe_x
	self:setPositionX(self._initPosX)

    -- msgList
    local function scrollViewEvent(sender, eventType)
    	-- print("IMRoomView scrollEvent = " .. eventType)
		executeFunc(self._onListScroll, sender, eventType)
	end
    self._msgList = self._ui.ListView
    self._msgSize = self._msgList:getContentSize()
    self._msgList:removeAllItems()
	self._msgList:addScrollViewEventListener(scrollViewEvent)
    self._msgList.createRender = function (list, idx)
    	local items = list:getItems()
    	local render = items[idx]
    	if nil == render then
			render = self:_createRender()
			list:pushBackCustomItem(render)
		end
		render:setVisible(true)
		return render
	end

	-- IMMsgRender 的node都从这里clone
	-- local node = cc.CSLoader:createNode(Res.IMMessageNode)
	-- self._renderNode = node:getChildByName("Panel")
	-- self._renderNode:retain()
	-- self._renderNode:removeFromParent()
	-- local renderSize = self._renderNode:getContentSize()
	-- local size = cc.size(self._msgList:getContentSize().width, renderSize.height)
	-- self._renderNode:setContentSize(size)
	-- ccui.Helper:doLayout(self._renderNode)
	-- local head = self._renderNode:getChildByName("head")
	-- local zOrder = head:getLocalZOrder()
	-- local pos = cc.p(head:getPosition())
	-- local panel = head:getChildByName("Panel")
	-- panel:retain()
	-- panel:removeFromParent()
	-- self._renderNode:addChild(panel, zOrder)
	-- panel:setPosition(pos)
	-- panel:setName("head")
	-- panel:release()
	-- head:removeFromParent()
	-- node = nil

	self._boxPanel = nil

    local btns = {}
    local btnCon = self._ui["im/Panel_tab"]
    btns[1] = btnCon:getChildByName("Panel_channel_1")
    btns[2] = btnCon:getChildByName("Panel_channel_2")
    btns[3] = btnCon:getChildByName("Panel_channel_3")
    btns[4] = btnCon:getChildByName("Panel_channel_4")
    btns[6] = btnCon:getChildByName("Panel_channel_5")
    btns[7] = btnCon:getChildByName("Panel_channel_6")
    btns[8] = btnCon:getChildByName("Panel_channel_7")

    local function onTabsBtn(index, btn)
    	if self._channelIndex then
	    	self._channelIndex = index
	    	self:switchChannel()
	    else
	    	self._channelIndex = index
	    end
    end
    local function onSelectBtn(btn, b)
    	btn:getChildByName("name"):setTextColor(b and display.COLOR_WHITE or cc.c3b(134,126,109))
    end
    self._tabsBtn = TabsBtn.new(btns, onTabsBtn, nil, nil, onSelectBtn)

	-- teamreq tip
	-- self._teamreqTip = display.addNewPoint(btnCon:findChild("Search/tishi"))
	-- self:setTeamreqTipVisible(false)

    self._ui.Button_set:addClickEventListener(function()
    		executeFunc(self._onOperate, "openSetView")
    	end)
    self._ui.Button_close:addClickEventListener(function()
    		executeFunc(self._onHideView)
    	end)
    -- display.nodeRemoveForNotHit(self._ui.im, function()
    -- 		executeFunc(self._onHideView)
    -- 	end)

    -- private
    self._priList = ListViewExtend.scrollToItemExtend(self._ui.ListView_private)
    self._priHeight = self._priList:getContentSize().height
    self._priList.createRender = function (list, idx)
    	local items = list:getItems()
    	local render = items[idx]
    	if nil == render then
			render = IMPriRender.create()
			list:pushBackCustomItem(render)
		end
		render:setVisible(true)
		return render
	end
    self._priList.insertRender = function (list, idx)
		local render = IMPriRender.create()
		list:insertCustomItem(render, idx)
		return render
	end

	self._ui.Button_add:addClickEventListener(function(sender)
			executeFunc(self._onOperate, "addTarget")
    	end)

    -- msg tips
    display.uiAddClick(self._ui.Panel_message_tips, function()
    		executeFunc(self._onOperate, "showNewMsg")
    	end)

    -- input
    self._inputWord = self._ui.Panel_bom_1
    self._inputVoice = self._ui.Panel_bom_2
    self._inputWord:setVisible(true)
	self._inputVoice:setVisible(false)
	-- 海外版没有语音功能
	if app:getPublisher() ~= Enums.Publisher.tencent then
		self._inputWord:getChildByName("Button_keyboard"):setVisible(true)
		self._inputWord:getChildByName("Button_mike"):setVisible(false)
		self._inputWord:getChildByName("Button_keyboard"):setTouchEnabled(false)
	else
		self._inputWord:getChildByName("Button_keyboard"):setVisible(false)
		self._inputWord:getChildByName("Button_mike"):setVisible(true)
	end
	
	self._btnMore = self._inputWord:getChildByName("Button_more")
    self._inputWord:getChildByName("Button_mike"):addClickEventListener(function()
    		self._inputWord:setVisible(false)
    		self._inputVoice:setVisible(true)
    	end)
    self._btnMore:addClickEventListener(function(sender)
			self:switchBoxPanel(true)
    	end)
    self._inputWord:getChildByName("Button_enter"):addClickEventListener(function()
    		local str = self._editText:getText()
			if string.len(str) > 0 then
				executeFunc(self._onOperate, "enterWords", str)
			end
    	end)

    self._inputVoice:getChildByName("Button_keyboard"):addClickEventListener(function()
    		self._inputWord:setVisible(true)
    		self._inputVoice:setVisible(false)
    	end)
    self._inputVoice:getChildByName("Button_more"):addClickEventListener(function(sender)
    		self._inputWord:setVisible(true)
    		self._inputVoice:setVisible(false)
    		self:switchBoxPanel(true)
    	end)
    local mikeBtn = self._inputVoice:getChildByName("Button_mike")
    mikeBtn:setPressedActionEnabled(false)
    self._voiceRender = IMVoiceRender.create(mikeBtn, "current")
    self._voiceRender:onTouchEvent(function(isTouch)
    		self._inputVoice:getChildByName("Text_btn_1"):setVisible(not isTouch)
    		self._inputVoice:getChildByName("Text_btn_2"):setVisible(isTouch)
		end)
	
	self:_initEditBox()
	-- private redPoint
	self:setP2PBtnRedPoint(app:getInst("IMModel"):isShowP2PRedPoint()) 		
end

function ClassRef:_initEditBox()
	if not self._textField then
		self._textField = self._inputWord:getChildByName("TextField")
		self._textField:setVisible(false)
	end
	if self._editText then
		self._editText:removeFromParent()
		self._editText = nil
	end
	-- print("IMRoomView.initEditBox")

	local function onEditCallback(strEventName,sender)
		-- print("IMRoomView editEventName = " .. strEventName)
        local edit = sender
		if strEventName == "began" then
        elseif strEventName == "ended" then
        elseif strEventName == "return" then
            local str = self._editText:getText()
            -- print("return str = " .. str)
            if string.len(str) > 0 then
            	if string.ulen(str) > Constant.MAX_WORD_LEN then
            		str = string.usubstr(str, Constant.MAX_WORD_LEN)
            	end
            	-- self._editText:setText("")
	        	executeFunc(self._onOperate, "enterWords", str)
            end
        elseif strEventName == "changed" then
            if string.ulen(edit:getText()) > Constant.MAX_WORD_LEN then
                edit:setText(string.usubstr(edit:getText(), Constant.MAX_WORD_LEN))
            end
            executeFunc(self._onOperate, "wordsChange", edit:getText())
        end
	end

	self._editText = display.replaceTextFieldWithEditBox(self._textField, nil, nil, true)
	self._editText:registerScriptEditBoxHandler(onEditCallback)
end

function ClassRef:show()
	self:setVisible(true)

	-- 初始化 输入框，每次打开的时候都创建
	--self:_initEditBox()
	self._editText:setVisible(true)
	self:openAction()
end

function ClassRef:openAction()
	self:stopAllActions()
	local move = cca.moveTo(0.2, 0, 0)
	local act = cca.exponentialOut(move)
	self:runAction(act)
end

function ClassRef:closeAction(cb)
	self:stopAllActions()
	local move = cca.moveTo(0.2, self._initPosX, 0)
	local endCB = cca.cb(function() executeFunc(cb) end)
	local act = cca.seq({cca.exponentialIn(move), cca.hide(), endCB})
	self:runAction(act)
end

function ClassRef:hide(cb)
	-- self:setVisible(false)
	self:hidePanel()
	self._editText:setVisible(false)
	self:removeUnusedItem()

	self:closeAction(cb)
end

function ClassRef:onListScroll(cb)
	self._onListScroll = cb
end

function ClassRef:onBoxSwitch(cb)
	self._onBoxSwitch = cb
end

function ClassRef:onChannelSwitch(cb)
	self._onChannelSwitch = cb
end

function ClassRef:setTeamreqTipVisible(b)
	-- print("setTeamreqTipVisible", b)
	-- self._teamreqTip:setVisible(b)
	-- if b then
	-- 	display.resumeTimeline(self._teamreqTip)
	-- else
	-- 	display.pauseTimeline(self._teamreqTip)
	-- end
end

function ClassRef:switchChannel(index)
	if index then
		self._channelIndex = index
		self._tabsBtn:setSelected(index)
	end
	-- print("IMRoomView _channelIndex = " .. self._channelIndex)

	if self._channelIndex == 7 then
		self:setTeamreqTipVisible(false)
	end

	executeFunc(self._onChannelSwitch, self._channelIndex, self._msgList)

	self:hidePanel()
	self:refreshNewMsg(0)
end

function ClassRef:hidePanel()
	self:switchBoxPanel(false)
end

function ClassRef:switchBoxPanel(visible)
	-- print("IMRoomView.switchBoxPanel visible=" .. tostring(visible))
	visible = visible or false
	if visible then
		if nil == self._boxPanel then
			self._boxPanel = IMBoxPanel.create()
			-- self._boxPanel:setPosition(200, 600)
			self._root:addChild(self._boxPanel, 10)
			self._boxPanel:onBoxSwitch(self._onBoxSwitch)
			self._boxPanel:onNotHit(handler(self, self.switchBoxPanel))
		end
		self._boxPanel:stopAllActions()
		self._boxPanel:setVisible(true)
		self._boxPanel:switchList()
	else
		if self._boxPanel then
			self._boxPanel:setVisible(false)
		end
	end
end

--name 	= string 频道名字
--isOk 	= true/false 是否可以聊天
--tips = string 不能聊天的原因
function ClassRef:refreshTargets(name, isOk, tips)
	-- print("IMRoomView.refreshTargets isOk, tips", isOk, tips)

	self:setPriRender(nil)
	self._ui.Text_title:setString(name)

	-- 私聊与否
	local isPri = (self._channelIndex == 6)
	self._ui.Panel_private:setVisible(isPri)

	local newHeight = isPri and (self._msgSize.height - self._priHeight) or self._msgSize.height
	local curHeight = self._msgList:getContentSize().height
	if curHeight ~= newHeight then
		self._msgList:setContentSize(cc.size(self._msgSize.width, newHeight))
	end

	if isOk then
		self._inputWord:setVisible(true)
		self._inputVoice:setVisible(false)
		self._ui.Text_tips:setVisible(false)
	else
		self._inputWord:setVisible(false)
		self._inputVoice:setVisible(false)
		self._ui.Text_tips:setVisible(true)
		self._ui.Text_tips:setString(tips)
	end
end

function ClassRef:setInputWord()
    self._inputWord:setVisible(true)
    self._inputVoice:setVisible(false)
end

function ClassRef:canInputWord()
    return self._inputWord:isVisible()
end
function ClassRef:canInputVoice()
    return self._inputVoice:isVisible()
end

function ClassRef:setPriRender(render)
	if self._curPriRender then
		self._curPriRender:setSelected(false)
		self._curPriRender:setNum(0)
	end
	self._curPriRender = render
	if render then
		self._priList:scrollToItem(render)
		render:setSelected(true)
		render:setNum(0)
		local data = render:getData()
		local name = string.format(L("lua_code_text_478"), data.name)
		self._ui.Text_title:setString(name)

		self._inputWord:setVisible(true)
		self._inputVoice:setVisible(false)
		self._ui.Text_tips:setVisible(false)
	end
end

function ClassRef:getMsgItems()
	return self._msgList:getItems()
end

function ClassRef:getMsgList()
	return self._msgList
end

function ClassRef:getPriList()
	return self._priList
end

function ClassRef:removeUnusedItem(lenth)
	lenth = lenth or 20
	--删掉多余的item
	display.removeListUnuseItem(self._msgList, lenth)
end

function ClassRef:scrollToNew()
	self._msgList:requestRefreshView()
	self._msgList:forceDoLayout()
	self._msgList:scrollToBottom(0.2, false)
end

function ClassRef:jumpToNew()
	self._msgList:requestRefreshView()
	self._msgList:forceDoLayout()
	self._msgList:jumpToBottom()
end

function ClassRef:refreshNewMsg(count)
	self._ui.Panel_message_tips:setVisible(count > 0)
	if count > 0 then
		local text = self._ui.Panel_message_tips:getChildByName("Text")
		text:setString( string.format(L("lua_code_text_47"), count) )
	end
end

function ClassRef:_createRender()
	-- print("IMRoomView._createRender")
	-- local render = IMMsgRender.create(self._renderNode:clone())
	local node = cc.CSLoader:createNode(Res.IMMessageNode)
	ccui.Helper:doLayout(node)
	local size = node:getChildByName("Panel"):getContentSize()
	size.width = self._msgList:getContentSize().width
	node:setContentSize(size)
	local render = IMMsgRender.create(node)
	return render
end

function ClassRef:addNewMsgItem()
	local items = self._msgList:getItems()
	local idx = #items
	-- for i=#items, 1, -1 do
	-- 	if items[i]:isVisible() then
	-- 		idx = i
	-- 		break
	-- 	end
	-- end

	-- print("IMroomView.addNewMsgItem", idx)

	local render = self._msgList:createRender(idx + 1)
	local items = self._msgList:getItems()
	if #items > MESSAGE_MAX_NUM then
		self._msgList:removeItem(0)
	end
	return render
end

function ClassRef:addOldMsgItem()
	if #self._msgList:getItems() < MESSAGE_MAX_NUM then
		local render = self:_createRender()
		self._msgList:insertCustomItem(render, 0)
		return render
	end
	return nil
end

function ClassRef:appendWords(word)
	local str = self._editText:getText()
	local strLen = string.ulen(str)
	local wordLen = string.ulen(word)
	if (strLen + wordLen) <= Constant.MAX_WORD_LEN then
		self._editText:setText(str .. word)
	end
end

function ClassRef:clearWords()
	self._editText:setText("")
end

function ClassRef:remove()
	if self._boxPanel then self._boxPanel:remove() end
	-- self._renderNode:release()
end

-- 设置密聊小红点
function ClassRef:setP2PBtnRedPoint(b)
	self._tabsBtn:getBtn(6):getChildByName("dot"):setVisible(b)
end

return ClassRef
